<?php

/**
 * Base SGN application class.
 * Sets up the environment as necessary and acts as the registry for the application.
 * Can broker to the autoload as well.
 *
 * $Id$
 */
class SGN_SiteConfig
{
    /**
     *
     * Configuration instances
     *
     * @var array
     */
    private static $_configs;
    
    /**
     *
     * Singleton database instances
     *
     * @var array $_dbInstances
     *
     */
    private static $_dbInstances;
    
    /**
     *
     * Get configuration
     * Guarantee singelton
     *
     *
     * @param string $module
     * @param string $catalogue
     * @param string $configKey
     *
     * @return SGN_HandlerConfig object
     */
    public static function getConfig($module, $catalogue, $configKey = '')
    {
        /**
         * Check instance from $_configs
         * ...
         */
        if (self::$_configs[$module][$catalogue] instanceof SGN_HandlerConfig) {
            if ($configKey) {
                return self::$_configs[$module][$catalogue]->get($configKey);
            }
            return self::$_configs[$module][$catalogue];
        }
        
        if (!$module) {
            throw new Exception("Configuration namespace \"$module\" not found.");
        }
        
        if (!$catalogue) {
            throw new Exception("Configuration name \"$catalogue\" not found in namespace \"$module\"");
        }
        
        /**
         * Get cache
         * @var cache object
         */
        $cache = GlobalCache::getCacheInstance('config');
        $configKeyName = APPLICATION_ENV . ".configdb.$module.$catalogue"; // config.namespace.name
        
        $config = false;
//         $cacheConfig = Zend_Registry::get('configuration');
//         if (!$cacheConfig->cachingfarm->config->disable_staging && strpos($_SERVER['SERVER_NAME'], 'staging') === false) {
//             // disable for staging only
//             $config = $cache->getCache($configKeyName);
//         }
        
        if ($config === false) {

            /**
             * Get data of key $product.$catalogue.$key from DB (HandlerSocket)
             */
            if (!self::$_dbInstances[$module][$catalogue]) {
                self::$_dbInstances[$module][$catalogue] = Application_Model_DAO_SiteConfig_Adapter::factory();
            }
            
            //select config from db
            $input = self::$_dbInstances[$module][$catalogue]->selectOne(array($module,$catalogue), '=');
            $config = new SGN_HandlerConfig($input);
            $cache->setCache($configKeyName, $config);
        }
        
        self::$_configs[$module][$catalogue] = $config;
        if ($configKey) {
            return self::$_configs[$module][$catalogue]->get($configKey);
        }
        
        //return HandlerConfig object
        return self::$_configs[$module][$catalogue];
    }
}